import { useState } from "react";

export const EMAIL_REGEX = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;

export const validateEmail = (email: string): string => {
  if (!email.trim()) return "请输入邮箱地址";
  if (!EMAIL_REGEX.test(email.trim())) return "邮箱格式不正确";
  return "";
};

export const validatePassword = (password: string): string => {
  if (!password) return "请输入密码";
  return "";
};

export const validateCode = (
  code: string,
  requiredLength: number = 6
): string => {
  if (!code) return "请输入验证码";
  if (code.length !== requiredLength)
    return `验证码必须为 ${requiredLength} 位`;
  return "";
};

// 定义错误对象的类型
export interface FormErrors {
  [key: string]: string;
}

// 定义验证器函数类型
export type Validator = (value: string, ...args: any[]) => string;

export const useFormValidation = () => {
  const [errors, setErrors] = useState<FormErrors>({});

  const validateField = (
    field: string,
    value: string,
    validator: Validator,
    ...args: any[]
  ): boolean => {
    const error = validator(value, ...args);
    setErrors((prev) => ({ ...prev, [field]: error }));
    return !error;
  };

  return { errors, setErrors, validateField };
};
